package com.xcc.core.netty.client;


import java.math.BigInteger;

import com.xcc.core.netty.manager.ManagerChannel;
import com.xcc.core.netty.model.LengthModel;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class RealLengthClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

	private int id;


	public RealLengthClientHandler(int id) {
		this.id = id;
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx)
			throws Exception {
		//   int id=Integer.parseInt("0x"+ctx.channel().id().asShortText(), 16);
		int id=  new BigInteger(ctx.channel().id()
				.asShortText(), 16).intValue();
		System.out.println("代理客户端ID:"+id);
		ManagerChannel.getAllServer2().put(id+"",ctx.channel());
	 	int id1=  new BigInteger(ctx.channel().id().asShortText(), 16).intValue();
	//	System.out.println("发送给真服务id"+id1);
	//	ManagerChannel.channelMapper.put(id1+"", this.id+"");
		ManagerChannel.channelMapper.put(id+"", this.id+"");
		Channel  ch = ManagerChannel.getServerChannel("3389");
		LengthModel mLengthModel=new LengthModel();
	//	byte[] bs=("connected&"+id1).getBytes();
	 	byte[] bs= (""+id1).getBytes();
		mLengthModel.setId(this.id);
		mLengthModel.setBs(bs);
		mLengthModel.setType((byte)3);
		mLengthModel.setLength(bs.length);
		ch.writeAndFlush(mLengthModel);
	}

	//发送给服务端
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, 
			ByteBuf msg)
					throws Exception {
		LengthModel mLengthModel=new LengthModel();
		Channel  ch = ManagerChannel.getServerChannel("3389");
		byte[] bs=new byte[msg.readableBytes()];
		msg.readBytes(bs);
		mLengthModel.setBs(bs);
		mLengthModel.setLength(bs.length);
		int id=  new BigInteger(ch.id()
				.asShortText(), 16).intValue();
		int id1=  new BigInteger(ctx.channel().id()
				.asShortText(), 16).intValue();
		System.out.println("3389id"+ManagerChannel.getChannelmapper().get(id1+""));

		if(ManagerChannel.getChannelmapper().get(id1+"")==null) {
			System.out.println("内部通信异常"); 
			System.out.println(id1);
			for(byte b:mLengthModel.getBs()) {
				System.out.print((0xff&b)+" ");
			}
			return;
		}

		mLengthModel.setId(Integer.parseInt(ManagerChannel.getChannelmapper().get(id1+"")));
		System.out.print("3389服务发送数据："); 
		for(byte b:mLengthModel.getBs()) {
			System.out.print((0xff&b)+" ");
		}
		mLengthModel.setType((byte)1);
		ch.writeAndFlush(mLengthModel);   


	}

}
